package com.compunit.composite.core;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.compunit.interfaces.IResourceRetriever;

/**
 * <code>ResourceRetriever</code> defines the implementation
 * of an utility unit that is responsible for retrieving
 * resources from a component's resource jar file.
 *
 * @author Yi Wang (Neakor)
 * @version Creation date: 11-21-2009 19:49 EST
 * @version Modified date: 12-05-2009 22:04 EST
 */
public class ResourceRetriever implements IResourceRetriever {
	/**
	 * The <code>URL</code> to the resources jar file.
	 */
	private final URL jarurl;
	/**
	 * The <code>JarFile</code> of the resources file.
	 */
	private final JarFile jar;
	/**
	 * The <code>Map</code> of <code>String</code> entry
	 * names to <code>byte</code> array cached data.
	 */
	private Map<String, byte[]> cache;
	
	/**
	 * Constructor of <code>ResourceRetriever</code>.
	 * @param directory The <code>URL</code> path
	 * to the directory that contains the component
	 * cx and class files.
	 * @param resourcename The <code>String</code>
	 * resources name in the cx definition.
	 * @param cache <code>true</code> if all data
	 * should be cached at construction time.
	 * @throws IOException If the given directory is
	 * invaid.
	 */
	public ResourceRetriever(final URL directory, final String resourcename, boolean cache) throws IOException {
		String raw = directory.getPath();
		if(!raw.endsWith("/")) raw.concat("/");
		final String path = raw.substring(raw.indexOf("/"), raw.length()).concat(resourcename).concat(".resources.jar");
		final File jarfile = new File(path);
		if(!jarfile.exists()) throw new IOException("Missing resources file: ".concat(jarfile.toString()));
		this.jarurl = jarfile.toURI().toURL();
		this.jar = new JarFile(jarfile);
		if(cache) {
			this.cache = new HashMap<String, byte[]>();
			Enumeration<JarEntry> entries = this.jar.entries();
			while(entries.hasMoreElements()) {
				final JarEntry entry = entries.nextElement();
				final byte[] data = this.readEntry(entry);
				this.cache.put(entry.getName(), data);
			}
		}
	}
	
	/**
	 * Read in the bytes associated with given jar entry.
	 * @param entry The <code>JarEntry</code> to be read.
	 * @return The <code>byte</code> array of data.
	 * @throws IOException If reading failed.
	 */
	private byte[] readEntry(final JarEntry entry) throws IOException {
		final InputStream input = this.jar.getInputStream(entry);
		final ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			final byte[] buffer = new byte[4096];
			while(true) {
				final int length = input.read(buffer);
				if(length < 0) break;
				output.write(buffer, 0, length);
			}
			return output.toByteArray();
		} finally {
			input.close();
			output.close();
		}
	}

	@Override
	public URL getResource(final String name) {
		try {
			final String path = "jar:".concat(this.jarurl.toString()).concat("!/").concat(name);
			return new URL(path);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public byte[] getResourceBytes(final String name) {
		if(this.cache != null) {
			return this.cache.get(name);
		}
		final JarEntry entry = this.jar.getJarEntry(name);
		try {
			return this.readEntry(entry);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
